import React, { Component } from 'react'
import ReactDom from 'react-dom'
import { Router, Route, Link, IndexLink, hashHistory, IndexRoute } from 'react-router'
import * as Actions from "../actions"
import async from "Async"

export default class RecommendationList extends Component {
    constructor(props) {
        super(props)
        this.state = { recommendationList: {} }
    }
    _toLeft(index) {
        console.log("_toLeft", index)
        let {recommendationList} = this.state
        let recommendation = recommendationList[index]
        let prebooksLen = recommendation.prebooks.length
        let booksLen = recommendation.books.length
        if ((recommendation && recommendation.books.length > 5) && (recommendation.prebooks[prebooksLen - 1] !== recommendation.books[booksLen - 1])) {
            let currentIndex = ""
            recommendation.books.map((bookId, i) => {
                if (recommendation.prebooks[prebooksLen - 1] === bookId) {
                    currentIndex = i
                }
            })
            let newBookId = recommendation.books[currentIndex + 1]
            if (newBookId) {
                let newPreBooks = recommendation.prebooks.concat([])
                newPreBooks.shift();
                newPreBooks.push(newBookId)
                recommendation = Object.assign({}, recommendation, { prebooks: newPreBooks })
                console.log("after: ", recommendation)
                // recommendationList.splice(index, 1, recommendation)
                let newRecommendationList = recommendationList.map((rec, j) => {
                    if (j === index) {
                        return recommendation
                    } else {
                        return rec
                    }
                })
                console.log("after: ", newRecommendationList)
                this.setState(Object.assign({}, { recommendationList: newRecommendationList }))
            }
        }
    }
    _toRight(index) {
        console.log("_toRight", index)
        // let {recommendationList} = this.state
        // let recommendation = recommendationList[index]
        // if ((recommendation && recommendation.books.length > 5) && (recommendation.prebooks[0] !== recommendation.books[0])) {
        //     let currentIndex = ""
        //     recommendation.books.map((bookId, i) => {
        //         if (prebooks[0] === bookId) {
        //             currentIndex = i
        //         }
        //     })
        //     let newBookId = recommendation.books[currentIndex + 5]
        //     if (newBookId) {
        //         recommendation.prebooks.shift();
        //         recommendation.prebooks.push(newBookId)
        //         recommendationList = recommendationList.splice(index, 1, recommendation)
        //         this.setState(Object.assign({}, this.state, { recommendationList }))
        //     }
        // }
    }
    componentDidMount() {
        // let {recommendationList} = this.state;
        // getRecommendationList().then(function (res) {
        //     console.log("recommendationList: ", res)
        //     recommendationList = res.map((rec, index) => {
        //         let prebooks = rec.books.slice(0, 5)
        //         rec = Object.assign({}, rec, { prebooks })
        //         return rec
        //     })
        //     console.log("pre: ", recommendationList)
        //     this.setState(Object.assign({}, this.state, { recommendationList: recommendationList }))
        // }.bind(this), (reason) => {
        //     console.log("getRecommendationList err: ", reason)
        //     throw reason
        // })
    }
    render() {
        let {recommendationList} = this.state
        console.log("length:", recommendationList.length)
        let homeRecommendation = <div></div>
        let firstRecommendation = {}
        if (recommendationList.length > 0) {
            homeRecommendation = recommendationList.map((rec, i) => {
                if (rec.sortValue === 0) {
                    let booklist = rec.prebooks.map((bookId, j) => {
                        return <Book key={j} bookId={bookId} />
                    })
                    return <div key={i} style={{ paddingBottom: "30px" }}>
                        <div className="books-rec-head">
                            <span>{rec.title}</span>
                        </div>
                        <div style={{ height: "260px", marginTop: "10px" }}>
                            <div className="books-rec-books">
                                <div name="carousel" style={{ marginLeft: "-19px" }}>
                                    {booklist}
                                </div>
                            </div>
                        </div>
                    </div>
                } else if (rec.sortValue === 100) {
                    firstRecommendation = rec
                }
            })
        }
        return <div>

            {recommendationList[0] ?
                <div>
                    <div style={{ backgroundColor: "#FFFFFF", border: "#D9DADA 1px solid", borderTop: "#5A79E4 2px solid" }}>
                        <Roller recommendation={firstRecommendation }/>
                        {homeRecommendation}
                    </div>
                </div>
                : null}
        </div>
    }
}

class Roller extends Component {
    constructor() {
        super()
        this.state = { currentIndex: 0, books: [] }
    }
    left() {
        let {books} = this.props.recommendation;
        let {currentIndex} = this.state
        if (currentIndex == 0) {
            currentIndex = books.length - 1
        } else {
            currentIndex--
        }
        this.setState({ currentIndex })

    }
    right() {
        let {books} = this.props.recommendation;
        let {currentIndex} = this.state
        if (currentIndex == books.length - 1) {
            currentIndex = 0
        } else {
            currentIndex++
        }
        this.setState({ currentIndex })

    }
    componentDidMount() {
        let {books} = this.props.recommendation;
        if (books) {
            let books_ = []
            async.series(books.map(bookId => (callback) => {
                Actions.getBook(bookId).then(book => {
                    console.log("accese")
                    books_.push(book)
                    callback(null)
                })
            }), (err) => {
                console.log("err ")
                this.setState({ books: books_ })
            })
        }
    }
    onClickBook(book) {
        window.location = `#/readbook/${book.bookId}`
    }
    render() {
        let {books} = this.state;
        return <div style={{ position: "relative", height: 350, margin: 35 }}>
            <div style={{ position: "absolute", left: 5, top: "45%" }} onClick={() => this.left()}><i className="fa fa-angle-left fa-3x"></i></div>
            <div style={{ position: "absolute", right: 5, top: "45%" }} onClick={() => this.right()}><i className="fa fa-angle-right fa-3x"></i></div>
            <div style={{ position: "relative" }}>
                {books && books.length >= 5 ?
                    [-2, -1, 0, 1, 2].map(i => (this.state.currentIndex + books.length + i) % books.length).map(i => { console.log(i); return books[i] })
                        .map((book, i) => {
                            return <div key={i} style={{ zIndex: Math.round(Math.cos((2 - i) / 3) * 1000), position: "absolute", left: "50%", marginLeft: Math.sin((i - 2) / 2) * 300 }}>
                                <img role="button" onClick={() => this.onClickBook(book)} style={{ marginTop: (1 - Math.cos((2 - i) / 2)) / 2 * 320, marginLeft: -Math.cos((2 - i) / 2) * 250 / 2, width: Math.cos((2 - i) / 2) * 250, height: Math.cos((2 - i) / 2) * 320 }} src={`bookService/getBookCover/${book.cover}`} />
                            </div>
                        }
                        ) : null
                }
            </div>
        </div>
    }
}

const getRecommendationList = () => {
    return fetch("/recommendationService/getRecommendations", {
        method: 'POST', headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        }, body: JSON.stringify({})
    })
        .then(res => res.json())
}

const getBook = (bookId) => {
    return fetch("/bookService/getBook", {
        method: 'POST', headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        }, body: JSON.stringify({ bookId: bookId })
    })
        .then(res => res.json())
}

class Book extends Component {
    constructor(props) {
        super(props)
        this.state = { book: {} }
    }
    componentDidMount() {
        let {bookId} = this.props
        let {book} = this.state
        getBook(bookId).then(function (res) {
            // console.log("getBook res: ", res);
            book = res
            this.setState(Object.assign({}, this.state, { book }))
        }.bind(this), (reason) => {
            console.log("getBook err: ", reason)
            throw reason
        })
    }
    render() {
        let {book} = this.state
        let cover = book.cover ? ("http://localhost:8080/bookService/getBookCover/" + book.cover) : "/dist/images/book.jpg"
        return <div className="books-rec-book">
            <img src={cover} />
            <a href={`#/readbook/${book.bookId}`} className="books-only-two">{book.name}</a>
            <span className="books-only-one">{book.author}</span>
        </div>

    }
}
